package ynu.edu.online_course.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ynu.edu.online_course.entity.Course;
import ynu.edu.online_course.entity.UserRole;
import ynu.edu.online_course.mapper.CourseMapper;
import ynu.edu.online_course.mapper.UserRoleMapper;
import ynu.edu.online_course.service.CourseService;
import ynu.edu.online_course.service.UserExtensionService;

import java.util.List;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private UserExtensionService userExtensionService;
    @Autowired
    private CourseMapper courseMapper;

    @Override
    public void addCourse(Course course, Long userId) {
        if (isCourseAdmin(userId)) {
            courseMapper.insertCourse(course);
        } else {
            throw new SecurityException("您没有权限新增课程");
        }
    }

    @Override
    public void updateCourse(Course course, Long userId) {
        if (isCourseAdmin(userId)) {
            courseMapper.updateCourse(course);
        } else {
            throw new SecurityException("您没有权限更新课程");
        }
    }

    @Override
    public void deleteCourse(Long courseId, Long userId) {
        if (isCourseAdmin(userId)) {
            courseMapper.deleteCourse(courseId);
        } else {
            throw new SecurityException("您没有权限删除课程");
        }
    }

    @Override
    public List<Course> getAllCourses() {
        return courseMapper.findAll();
    }

    UserRoleMapper userRoleMapper;

    private boolean isCourseAdmin(Long userId) {
        List<UserRole> userRoles = userRoleMapper.findRolesByUserId(userId);
        return userRoles.stream()
                .anyMatch(role -> 2==role.getRole().getId());
    }

}
